package com.vinhvt.effiport.financial.ep;

import java.util.ArrayList;
import java.util.List;

public class Portfolio {
	private List<Asset> portfolio = new ArrayList<Asset>();				
	
	public double getVariance() {
		return calcVariance();		
	}
	
	public double getProfit() {
		return calcProfit();
	}
	
	public double getTotalWeight() {
		return calcTotalWeight();
	}						
	
	// ADDING Operation
	public void addAsset(Asset asset, double weight) {
		asset.setWeight(weight);
		this.portfolio.add(asset);						
	}		
	
	public void removeAssetAt(int position) {
		this.portfolio.remove(position);		
	}
	
	public Asset getAssetAt(int position) {
		return this.portfolio.get(position);
	}
	
	public void clear() {
		this.portfolio.clear();		
	}
	//
	
	/** Get Number */
	public int getNumberOfAsset() {
		return this.portfolio.size();
	}
	
	/** Calculate the Profit of Portfolio */
	private double calcProfit() {
		double result = 0.0;
		
		for(int i = 0; i < this.getNumberOfAsset(); i++) {
			Asset asset = this.getAssetAt(i);
			result += (asset.calcAverageReturn() * asset.getWeight());			
		}
		
		return result;
		
	}
	
	/** Calculate the Total Weight of all Asset in Portfolio */
	private double calcTotalWeight() {
		double result = 0.0;
		
		for(int i = 0; i < this.getNumberOfAsset(); i++) {
			Asset asset = this.getAssetAt(i);
			result += asset.getWeight();		
		}
		
		return result;
		
	}
	
	/** Calculate the Variance of Portfolio */
	private double calcVariance() {
		double result = 0.0;
		
		int size = this.portfolio.size();
		for(int i = 0; i < size; i++) {
			Asset asset1 = this.getAssetAt(i);
			for(int j = 0; j < size; j++) {
				Asset asset2 = this.getAssetAt(j);
				double cov = asset1.calcCovarWith(asset2);
				result += asset1.getWeight() * asset2.getWeight() * cov;
			}
		}
		
		return result;
	}
	
	@Override
	public String toString() {
		String result = "\nTICKER | WEIGHT";
		
		result += "\n-------|--------";
		for(int i = 0; i < this.portfolio.size(); i++) {
			Asset asset = this.getAssetAt(i);
			String symbol = asset.getSymbol();
			double weight  = asset.getWeight();
			result += "\n" + symbol + "    |    " + weight;
		}
		result += "\nVariance: " + this.calcVariance();
		result += "\nProfit: " + this.getVariance();
		
		return result;
	}
	
}
